import React, { useState, useCallback } from "react";
import { NextPage } from "next";
import Link from "next/link";
import dayjs from "dayjs";
import { Badge, Divider, Popconfirm, message, Select, Modal, Spin } from "antd";

import { AdminLayout } from "@/layout";
import { SPTDataTable } from "@/components/SPTDataTable";
import { PageApi } from "@/api/page";
import { ViewChart } from '@/components/ViewChart'
import { ViewApi } from "@/api/view";

const Page: NextPage = () => {
  const [visible, setVisible] = useState(false);
  const [views, setViews] = useState<IView[]>([]);
  const [loading, setLoading] = useState(false);
  const [pages, setPages] = useState(null);
  const [params, setParams] = useState(null);

  // 获取所有页面
  const getPages = useCallback(params => {
    setLoading(true)
    return PageApi.getAll(params).then(res => {
      setLoading(false);
      setPages(res[0]);
      setParams(params);
      return res;
    })
  }, [])
  // 删除页面
  const deletePage = id => {
    PageApi.deletePage(id).then(res => {
      message.success("删除成功")
      getPages(params);
    })
  }
  // 切换页面状态
  const toggleState = (page) => {
    page.status = page.status === 'publish' ? 'draft' : 'publish';
    PageApi.updatePage(page.id, page).then(res => {
      if (res.status === 'publish') {
        message.success("启用成功");
      } else {
        message.success("禁用成功")
      }
      getPages(params)
    })
  }

  const columns = [
    {
      title: '名称',
      key: 'name',
      dataIndex: 'name'
    },
    {
      title: '路径',
      key: 'path',
      dataIndex: 'path'
    },
    {
      title: '阅读量',
      key: 'views',
      render: (_, record) => (
        <Badge count={record.views} showZero={true} overflowCount={Infinity} style={{ backgroundColor: '#52c41a' }} />
      )
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => {
        const isPublish = record.status === 'publish';
        return (
          <Badge status={isPublish ? 'success' : 'warning'} text={isPublish ? "已发布" : "草稿"} />
        )
      }
    },
    {
      title: "发布时间",
      key: 'publishAt',
      render: (_, record) => (dayjs(record.publishAt).format("YYYY-MM-DD hh:mm:ss"))
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <span>
          <a onClick={() => toggleState(record)}>{record.status === 'publish' ? '禁用' : '启用'}</a>
          <Divider type="vertical" />
          <Link href={`/page/editor/${record.id}`}>
            <a target="_blank">编辑</a>
          </Link>
          <Divider type="vertical" />
          <a onClick={() => {
            setLoading(true);
            ViewApi.getViewsByUrl(window.location.href).then(res => {
              setViews(res);
              setTimeout(() => {
                setLoading(false);
              }, 500)
            })
            setVisible(true)
          }}>查看访问</a>
          <Divider type="vertical" />
          <Popconfirm okText="删除" cancelText="取消" title="删除这个页面吗？" onConfirm={() => deletePage(record.id)}>
            <a>删除</a>
          </Popconfirm>
        </span>
      )
    }
  ]
  return (
    <AdminLayout>
      <SPTDataTable data={pages} columns={columns} defaultTotal={0} onSearch={getPages} searchFields={[
        {
          label: '名称',
          field: 'name',
          msg: '输入页面名称'
        },
        {
          label: '路径',
          field: 'path',
          msg: '输入页面路径'
        },
        {
          label: '状态',
          field: 'status',
          children: (
            <Select style={{ width: 180 }}>
              <Select.Option key="publish" value="publish">已发布</Select.Option>
              <Select.Option key="draft" value="draft">草稿</Select.Option>
            </Select>
          )
        }
      ]} />
      <Modal title="访问统计" visible={visible} footer={false} closable={true} onCancel={() => {
        setViews([]);
        setVisible(false)
      }}>
        {
          loading ? (
            <Spin spinning={loading}></Spin>
          ) : (<ViewChart data={views} />)
        }
      </Modal>
    </AdminLayout>
  );
};

export default Page;
